package de.bazinga.rotw.objects;

import com.jme.bounding.BoundingBox;
import com.jme.math.Vector3f;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.shape.Box;
import com.jmex.game.state.GameStateManager;

import de.bazinga.rotw.collision.CollidableObjects;
import de.bazinga.rotw.game.RotwGameState;
import de.bazinga.rotw.network.BasicSyncManager;
import de.bazinga.rotw.network.Client;
import de.bazinga.rotw.network.Server;
import de.bazinga.rotw.network.message.ItemMessage;
import de.bazinga.rotw.person.Person;
import de.bazinga.rotw.sound.Sound;
import de.bazinga.rotw.texture.TextureCache;
import de.bazinga.rotw.weapon.Rifle;

public class RifleGunItem extends Node implements GameObject {
	private static final long serialVersionUID = 1L;
	
	private long hideTime = 0;

	public RifleGunItem(Vector3f min, Vector3f max) {
		
		Box item = new Box("ammo",min,max);
		
		item.setLightCombineMode(Spatial.LightCombineMode.Off);
		
		item.setModelBound(new BoundingBox());
		item.updateModelBound();
		
		item.setRenderState(TextureCache.getInstance().getTexture("texture/rifle.jpg"));
		item.updateRenderState();
		
		setCullHint(CullHint.Never);
		this.attachChild(item);
	}

	
	public void onCollision(Person person, boolean sendMessage) {
		if(getCullHint() == CullHint.Never) {
			if(person.getWeapon(Rifle.class) == null) {
				Rifle rifle = new Rifle();
				person.addWeapon(rifle);
			}else{
				person.getWeapon(Rifle.class).refillAmmo();
			}
			
			if(sendMessage) {
				// Tell Server that we updated
				ItemMessage itemMsg = new ItemMessage();
				itemMsg.setItem(ItemMessage.ITEM_RIFLE);
				itemMsg.setItemIndex(CollidableObjects.getInstance().getObjects("gameObjects").indexOf(this));
				itemMsg.setHide(true);
				
				BasicSyncManager syncManager = 
					((RotwGameState)GameStateManager.getInstance().getChild("gameState")).getSyncManager();
				if(syncManager instanceof Client) {
					((Client) syncManager).getClient().sendToServer(itemMsg);
				}else{
					((Server) syncManager).getServer().sendToAll(itemMsg);
				}
			}
			
			Sound.getInstance().getAudioTrack("sounds/reload.wav").play();
			
			hide();
		}
	}
	

	
	public void hide() {
		hideTime = System.currentTimeMillis();
		((RotwGameState)GameStateManager.getInstance().getChild("gameState")).addItemToRespawn(this);
		this.setCullHint(CullHint.Always);
	}
	
	private int getRespawnTime() {
		return 120000;
	}
	
	public boolean respawn() {
		if( (System.currentTimeMillis() - hideTime) > getRespawnTime()) {
			this.setCullHint(CullHint.Never);
			return true;
		}
		return false;
	}
}